<template>
  <div>
    <my-chart class="relative z-20" :default-option="defaultOption" :option="dataOption"></my-chart>
    <div class="absolute w-100% h-100% left-0 top-0 z-1">
      <img class="w-100% h-100%" :src="bgurl" />
    </div>
  </div>

</template>

<script>
import myChart from "./my-chart.vue";
export default {
  components: { myChart },
  props: ["colors", "update", "imgurl", "option", "dz", "dc","bgurl"],
  data: () => ({
    dataOption: {},
  }),
  computed: {
    defaultOption() {
      return this.option || {};
    },
  },
  methods: {
    initOption(imgurl) {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      const img = new Image();
      img.onload = () => {
        const width = (canvas.width = Math.floor(img.width / 2));
        const height = (canvas.height = Math.floor(img.height / 2));
        ctx.drawImage(img, 0, 0, width, height);
        const imgData = ctx.getImageData(0, 0, width, height);
        const data = [];
        for (let i = 0; i < imgData.data.length / 4; i++) {
          const r = imgData.data[i * 4];
          const g = imgData.data[i * 4 + 1];
          const b = imgData.data[i * 4 + 2];
          const x = i % width;
          const y = height - Math.floor(i / width);
          const sp = 5;
          if (x % sp == 0 && y % sp == 0 && x / sp % 2 == 1 && y / sp % 2 ==1) {
            const { z, c, name } = this.getXYConfig(x, y, r, g, b);
            const value = [x, y, z];
            const itemStyle = { color: c };
            const di = { value, itemStyle };
            if (name) {
              di.name = name;
            }
            if (z > 0) {
              data.push(di);
            }
          }
        }
        //
        this.dataOption = { series: [{ data }] };
      };
      img.src = imgurl;
    },
    getXYConfig(x, y, r, g, b) {
      const cs = this.colors || [];
      const dz = this.dz || 10;
      const dc = this.dc || `rgb(${[r, g, b].join(",")})`;
      //
      let res = { z: dz, c: dc };
      if (cs.length == 0) {
        return res;
      }
      for (const cd of cs) {
        const { x: xr, y: yr, z = dz, c = dc, name } = cd;
        let bool = true;
        if (xr[0] >= 0) {
          bool &= x >= xr[0];
        }
        if (xr[1] > 0) {
          bool &= x <= xr[1];
        }
        if (yr[0] >= 0) {
          bool &= y >= yr[0];
        }
        if (yr[1] > 0) {
          bool &= y <= yr[1];
        }
        if (bool) {
          return { z, c, name };
        }
      }

      return res;
    },
  },
  watch: {
    colors: {
      handler() {
        this.initOption(this.imgurl);
      },
      deep: true,
    },
    dz() {
      this.initOption(this.imgurl);
    },
    dc() {
      this.initOption(this.imgurl);
    },
  },
  created() {
    this.initOption(this.imgurl);
  },
};
</script>
